package util

import (
	"crypto/md5"
	"fmt"
	"github.com/go-resty/resty/v2"
	"io"
	"io/ioutil"
	"os"
	"unsafe"
)

// 解密m4s
func DecodeM4s(inputPath string, outputPath string, progressCallBack func(p float32)) bool {
	input, err := os.Open(inputPath)
	if err != nil {
		if progressCallBack != nil {
			progressCallBack(-1)
		}
		return false
	}
	defer input.Close()
	output, err := os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
	if err != nil {
		if progressCallBack != nil {
			progressCallBack(-1)
		}
		return false
	}
	defer output.Close()
	flag := true
	stat, err := input.Stat()
	if err != nil {
		if progressCallBack != nil {
			progressCallBack(-1)
		}
		return false
	}
	fileLen := stat.Size()
	convertLen := 0
	p := 0
	for {
		buffer := make([]byte, 1024, 1024)
		cnt, err := input.Read(buffer)
		if err == io.EOF && cnt == 0 {
			if progressCallBack != nil {
				progressCallBack(100)
			}
			return true
		}
		if flag {
			flag = false
			buffer = append(buffer[9:10], buffer[10:]...)
			buffer[3] = 0x20
			if !(buffer[16] == 0x69 && buffer[17] == 0x73 && buffer[18] == 0x6f) {
				buffer = append(buffer[:16], buffer[20:]...)
			}
		}
		convertLen += len(buffer)
		p++
		if p >= 10 {
			progressCallBack(float32(convertLen) / float32(fileLen) * float32(100))
			p = 0
		}
		_, err = output.Write(buffer)
		if err != nil {
			if progressCallBack != nil {
				progressCallBack(-1)
			}
			return false
		}
	}
}

// 获取文件的尺寸
func GetFileSize(filePath string) int64 {
	stat, err := os.Stat(filePath)
	if err != nil {
		return 0
	}
	return stat.Size()
}

// 字符串数组去重
func RemoveRepeatedElement(arr []string) []string {
	var newArr []string
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return newArr
}

// 是否有字符串为空
func IsAnyBlank(ars ...string) bool {
	for i := range ars {
		if ars[i] == "" {
			return true
		}
	}
	return false
}

// Bytes转String
func BytesToString(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

// 获得文件md5值
func GetMd5(filepath string) string {
	f, err := os.Open(filepath)
	if err != nil {
		return ""
	}
	defer f.Close()
	body, err := ioutil.ReadAll(f)
	if err != nil {
		return ""
	}
	return fmt.Sprintf("%x", md5.Sum(body))
}

// GET方式访问http，不接收返回值
func HttpGetWithResult(url string) {
	client := resty.New()
	_, _ = client.R().
		EnableTrace().
		Get(url)
}
